<?php
class V_Config
{
	public $config = array();
	public $isLoaded = array();
	public $mainConf;
	
	public function __construct()
	{
		$this->config = $this->getConfig();
	}
	
	public function getConfig()
	{
		if ( ! isset($this->mainConf))
		{
			$configPath = VPATH_MYAPP.DS.'config'.DS.'config.php';
			if ( ! file_exists($configPath))
			{
				exit('The configuration file '.$configPath.' does not exist.');
			}

			require($configPath);

			if ( ! isset($CONFIG) OR ! is_array($CONFIG))
			{
				exit('Your config file does not appear to be formatted correctly.');
			}

			$this->mainConf[0] =& $CONFIG;
		}
		return $this->mainConf[0];
	}
	
	/**
	 * Load Config File
	 *
	 * @access	public
	 * @param	string	the config file name
	 * @return	boolean	if the file was loaded correctly
	 */	
	public function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
	{
		$file = ($file == '') ? 'config' : str_replace('.php', '', $file);
	
		if (in_array($file, $this->isLoaded, TRUE))
		{
			return TRUE;
		}

		$configPath = VPATH_MYAPP.DS.'config'.DS.$file.'.php';
		if ( ! file_exists($configPath))
		{
			if ($fail_gracefully === TRUE)
			{
				return FALSE;
			}
			die('The configuration file '.$file.'.php does not exist.');
		}
	
		include($configPath);

		if ( ! isset($CONFIG) OR ! is_array($CONFIG))
		{
			if ($fail_gracefully === TRUE)
			{
				return FALSE;
			}
			die('Your '.$file.'.php file does not appear to contain a valid configuration array.');
		}

		if ($use_sections === TRUE)
		{
			if (isset($this->config[$file]))
			{
				$this->config[$file] = array_merge($this->config[$file], $CONFIG);
			}
			else
			{
				$this->config[$file] = $CONFIG;
			}
		}
		else
		{
			$this->config = array_merge($this->config, $CONFIG);
		}

		$this->isLoaded[] = $file;
		unset($CONFIG);

		die('Config file loaded: config/'.$file.'.php');
		return TRUE;
	}
  	
	// --------------------------------------------------------------------

	/**
	 * Fetch a config file item
	 *
	 *
	 * @access	public
	 * @param	string	the config item name
	 * @param	string	the index name
	 * @param	bool
	 * @return	string
	 */
	public function item($item, $index = '')
	{	
		if ($index == '')
		{	
			if ( ! isset($this->config[$item]))
			{
				return FALSE;
			}

			$pref = $this->config[$item];
		}
		else
		{
			if ( ! isset($this->config[$index]))
			{
				return FALSE;
			}

			if ( ! isset($this->config[$index][$item]))
			{
				return FALSE;
			}

			$pref = $this->config[$index][$item];
		}

		return $pref;
	}
	
	/**
	 * Set a config file item
	 *
	 * @access	public
	 * @param	string	the config item key
	 * @param	string	the config item value
	 * @return	void
	 */
	public function setItem($item, $value)
	{
		$this->config[$item] = $value;
	}
}
